import React, {memo, useEffect, useRef, useState} from 'react';
import {DatePicker, message, Modal, Space, Upload} from "antd";
import moment from 'moment';

import "./management.css";
import Header from "../../../components/main-header/Header";
import {deepClone} from "../../../common/utils";
import {useSelector} from "react-redux";
import request from "../../../services/request";
import {ADMIN, GUEST, USER} from "../../../common/userRole";
import {BASE_URL} from "../../../services/config";
import headImgUrl from "./images/head1.png";

export default memo(function Management() {
  const [isShowAlert, setIsShowAlert] = useState(false);  //  是否显示删除对话框
  const {userInfo, isCN} = useSelector(state => ({
    userInfo: state.loginReducer.info,
    isCN: state.languageReducer.isCN
  })); //  获得用户信息
  const [userObj, setUserObj] = useState(userInfo); //  当前登陆用户信息
  const [userShowLists, setUserShowLists] = useState([]); //  展示用户列表
  const passwordInput = useRef();
  let cloneUserObj = {};
  useEffect(getUserLists, []);  //  获取用户列表

  //  获取头像Base64
  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  //  上传之前的钩子
  function beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      isCN
        ? message.error('请上传JPG/PNG格式的文件')
        : message.error('Please upload JPG/PNG files');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      isCN
        ? message.error('图片不能超过2MB')
        : message.error('The image is too large, no more than 2MB');
    }
    return isJpgOrPng && isLt2M;
  }

  //  上传文件改变时的状态
  function handleChange(info) {
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, imageUrl => {
          cloneUserObj = deepClone(userObj, cloneUserObj);
          cloneUserObj = {...cloneUserObj, portrait: imageUrl};
          setUserObj(cloneUserObj);
        }
      );
    }
  }

  //  获取用户列表
  function getUserLists() {
    request({
      url: "/user/getUserLists"
    }).then(res => {
      setUserShowLists(res.data);
    });
  }

  //  展示列表的role
  function showUserRole(role) {
    switch (role) {
      case ADMIN:
        return "Super Admin";
      case GUEST:
        return "Guest";
      case USER:
        return "user";
      default:
        return role;
    }
  }

  //  添加新用户
  function addNewUser() {
    passwordInput.current.value = "";
    if (userObj.password === "") {
      isCN
        ? message.error("密码不能为空")
        : message.error("The password cannot be empty");
      return;
    }
    request({
      url: "/user/addNewUser",
      data: userObj,
      method: "post"
    }).then(res => {
      switch (res.code) {
        case 200:
          isCN
            ? message.info("添加用户成功")
            : message.info("Added user successfully");
          setUserShowLists(res.data);
          cloneUserObj = deepClone(userObj, cloneUserObj);
          cloneUserObj = {...cloneUserObj, portrait: "", username: "", password: ""};
          setUserObj(cloneUserObj);
          break;
        case 500:
          message.error(res.message);
          break;
        default:
          message.error("error");
      }
    });
  }

  //  修改用户信息
  function modifyUser() {
    passwordInput.current.value = "";
    if (userObj.password === "") {
      cloneUserObj = deepClone(userObj, cloneUserObj);
      cloneUserObj = {...cloneUserObj, password: userInfo.password};
    }
    request({
      url: "/user/modifyUser",
      data: userObj,
      method: "post"
    }).then(res => {
      switch (res.code) {
        case 200:
          isCN
            ? message.info("修改信息成功")
            : message.info("Modified information successfully");
          setUserShowLists(res.data);
          break;
        case 500:
          message.error(res.message);
          break;
        default:
          message.error("error");
          // TODO: 排查错误
          console.log(res);
      }
    });
  }

  //  删除用户
  function deleteUser() {
    passwordInput.current.value = "";
    setIsShowAlert(false);
    if (userInfo.id === userObj.id) {
      isCN
        ? message.error("当前用户无法删除")
        : message.error("The current user cannot be deleted");
      return;
    }
    request({
      url: "/user/deleteUser",
      data: userObj.id,
      method: "post"
    }).then(res => {
      switch (res.code) {
        case 200:
          isCN
            ? message.info("用户删除成功")
            : message.info("User deleted successfully");
          setUserShowLists(res.data);
          break;
        case 500:
          message.error(res.message);
          break;
        default:
          message.error("error");
          // TODO: 排查错误
          console.log(res);
      }
    });
  }

  //  选中用户后的响应
  function chooseUser(indey) {
    passwordInput.current.value = "";
    setUserObj({...userShowLists[indey], password: ""});
  }

  return (
    <div>
      <Header name={isCN ? "登陆管理" : "Login Management"} imgPosition="50px" iconStyle="headerImg"/>
      <section className="mainSection settingManagement">
        <div className="settingManagementPart0">
          <header>
            {
              userInfo.role === 0 ? <ul>
                <li onClick={addNewUser}>{isCN ? "添加新用户" : "Add New User"}</li>
                <li onClick={modifyUser}>{isCN ? "修改" : "Modify"}</li>
                <li onClick={() => setIsShowAlert(true)}>{isCN ? "删除" : "Delete"}</li>
              </ul> : <ul>
                <li onClick={modifyUser}>{isCN ? "修改" : "Modify"}</li>
              </ul>
            }
          </header>
          <div>
            <div>
              <Upload username="avatar"
                      listType="picture-card"
                      className="avatar-uploader"
                      showUploadList={false}
                      action={`${BASE_URL}/user/getUserLists`}
                      beforeUpload={beforeUpload}
                      onChange={handleChange}
              >
                <img src={userObj.portrait || headImgUrl} alt="头像" style={{width: "100%", borderRadius: "8px"}}/>
              </Upload>
            </div>
            <ul>
              <li>
                <div>{isCN ? "用户名" : "Name"}</div>
                <input value={userObj.username}
                       onChange={(e) => {
                         e.target.value = e.target.value.replace(/[\u0391-\uFFE5]/gi, '');
                         e.target.value.length >= 30 && (e.target.value = e.target.value.slice(0, 29));
                         cloneUserObj = deepClone(userObj, cloneUserObj);
                         cloneUserObj = {...cloneUserObj, username: e.target.value};
                         setUserObj(cloneUserObj);
                       }} type="text"
                />
              </li>
              <li>
                <div>{isCN ? "用户密码" : "User password"}</div>
                <input ref={passwordInput} onChange={(e) => {
                  cloneUserObj = deepClone(userObj, cloneUserObj);
                  cloneUserObj = {...cloneUserObj, password: e.target.value};
                  setUserObj(cloneUserObj);
                }} type="password"
                />
              </li>
              <li>
                <div>{isCN ? "用户权限" : "User Role"}</div>
                {
                  userInfo.role === 0 ? <select
                    value={userObj.role}
                    onChange={(e) => {
                      cloneUserObj = deepClone(userObj, cloneUserObj);
                      cloneUserObj = {...cloneUserObj, role: Number(e.target.value)};
                      setUserObj(cloneUserObj);
                    }} style={{textAlignLast: "center"}}
                  >
                    <option value={0}>Super admin</option>
                    <option value={1}>User</option>
                  </select> : <div className="userRoleStyle">{showUserRole(userInfo.role)}</div>
                }
              </li>
              <li>
                <div>{isCN ? "有效期" : "Password Expires"}</div>
                {
                  userInfo.role === 0 ? <Space direction="vertical">
                    <DatePicker value={moment(userObj.expires)}
                                allowClear={false}
                                inputReadOnly={true}
                                onChange={(time, timeString) => {
                                  cloneUserObj = deepClone(userObj, cloneUserObj);
                                  cloneUserObj = {...cloneUserObj, expires: timeString};
                                  setUserObj(cloneUserObj);
                                }} style={{marginLeft: "50px", borderRadius: "10px", border: "2px solid #213040", textAlignLast: "center"}} className="Expires"
                    />
                  </Space> : <div className="expiresStyle">{userInfo.expires}</div>
                }
              </li>
            </ul>
          </div>
        </div>
        {
          userInfo.role === 0 ? <div className="settingManagementPart1">
            <p>{isCN ? "用户列表" : "Existing Users List"}</p>
            <div>
              <ul>
                <li style={{color: "#fff", position: "absolute"}}>
                  <div style={{background: "transparent"}}/>
                  <div>{isCN ? "编号" : "ID"}</div>
                  <div>{isCN ? "用户名" : "Name"}</div>
                  <div>{isCN ? "权限" : "Role"}</div>
                </li>
                {
                  userShowLists.map((item, index) => (
                    <li key={item.id} style={{cursor: "pointer"}} onClick={() => chooseUser(index)}>
                      {item.portrait ? <div style={{backgroundImage: `url(${item.portrait})`}}/> : <div/>}
                      <div>{item.id}</div>
                      <div>{item.username}</div>
                      <div>{showUserRole(item.role)}</div>
                    </li>
                  ))
                }
              </ul>
            </div>
          </div> : null
        }
      </section>
      {
        isShowAlert ? <Modal
          title={isCN ? "删除" : "Delete"}
          visible={true}
          onOk={deleteUser}
          onCancel={() => {
            setIsShowAlert(false);
          }}
          okText={isCN ? "确定" : "YES"}
          cancelText={isCN ? "取消" : "NO"}
        >
          <p>{isCN ? "您确定要删除该用户吗?" : "Are you sure to delete this user?"}</p>
        </Modal> : null
      }
    </div>
  );
});